from rest_framework.views import APIView
from rest_framework.response import Response
from blog.models import Comment, User, Article
from blog.utils.jwt_auth import get_user_id


class CreateView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            user = request.data.get('user')
            article = request.data.get('article')
            content = request.data.get('content')
            comment = Comment()
            comment.user = User.objects.filter(id=user).first()
            comment.article = Article.objects.filter(id=article).first()
            comment.content = content
            comment.save()
            return Response({
                'status': 200,
                'msg': '创建成功'
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})


class DeleteView(APIView):
    def post(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')
            user_id = get_user_id(token)
            id = request.data.get('id')
            comment = Comment.objects.filter(id=id).first()
            if comment.user_id != user_id:
                return Response({
                    'status': 204,
                    'msg': '不是你的评论'
                })
            comment.status = 0
            comment.save()
            return Response({
                'status': 200,
                'msg': '删除成功'
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'err': e.args})
